package visao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.table.AbstractTableModel;

public class PopularJTable extends AbstractTableModel {
	private static final long serialVersionUID = 1L;

	private List<Map<String, Object>> dataset = null;
	private Map<String, Object> fields = null;
	private int columncount = 0;
	private String[] columns = null;
	
	public PopularJTable (ResultSet rs){
		try {
			this.columns = new String[rs.getMetaData().getColumnCount()];
			this.columncount = rs.getMetaData().getColumnCount();
			this.dataset = new ArrayList<Map<String, Object>>();
			while (rs.next()){
				this.fields = new HashMap<String, Object>();
				for (int i = 1; i < this.columncount; i++) {
				     this.columns[i-1] = new String();
				     this.columns[i-1] = rs.getMetaData().getColumnName(i).toUpperCase();
				     this.fields.put(this.columns[i-1], rs.getObject(i));
				}
				this.dataset.add(this.fields);
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}
	
	@Override
	public int getColumnCount() {
		return columncount;
	}

	@Override
	public int getRowCount() {
		return dataset.size();
	}
	
	@Override
	public String getColumnName(int column){
		return columns[column];
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Map<String, Object> row = dataset.get(rowIndex);
		return row.get(columns[columnIndex]);
	}
	
	public List<Map<String, Object>> getDataSet(){
		return dataset;
	}
	
	public Map<String, Object> getRow(int row){
		return dataset.get(row);
	}
	
	public void insertRow(Map<String, Object> rowvalue){
		dataset.add(rowvalue);
		fireTableDataChanged();
	}
	
	public void removedRow (int row) {
		dataset.remove(row);
		fireTableDataChanged();
	}
}

